package product

import (
	"chain_bridge_service/internal/services/product"
	"net/http"

	"chain_bridge_service/internal/code"
	"chain_bridge_service/internal/pkg/core"
	"chain_bridge_service/internal/pkg/validation"
)

type createRequest struct {
	Id          string `bson:"_id,omitempty" json:"id"`
	ProductName string `bson:"productName" json:"productName"`
	Fee         string `bson:"fee" json:"fee"`
	Months      int    `bson:"months" json:"months"`
	Type        string `bson:"type" json:"type"`
}

type createResponse struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

func (h *handler) Create() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createRequest)
		res := new(createResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				validation.Error(err)),
			)
			return
		}

		createData := new(product.CreateProductData)
		createData.Months = req.Months
		createData.Fee = req.Fee
		createData.Type = req.Type
		createData.ProductName = req.ProductName

		id, err := h.productService.Create(ctx, createData)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ProductCreateError,
				code.Text(code.ProductCreateError)).WithError(err),
			)
			return
		}

		res.Code = code.StatusOK
		res.Data = id
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}
